<template>
  <div ref="printDiv">
    <div class="example" v-show="spinning">
      <a-spin :spinning="spinning" />
    </div>

    <div v-show="!spinning">
      <div style="margin-bottom: 10px">
        <span v-if="record.assignee == record.owner||record.owner==null">
          <a-button type="primary" @click="check"> 审核 </a-button>
          <a-button
            v-if="btn_auth.indexOf('1') != -1"
            style="margin-left: 10px"
            @click="backDown"
          >驳回</a-button>
          <a-button
            v-if="btn_auth.indexOf('2') != -1"
            style="margin-left: 10px"
            @click="addSign"
          >任务委派</a-button>
          <a-button
            v-if="btn_auth.indexOf('3') != -1"
            style="margin-left: 10px"
            @click="turnTask"
          >任务转派</a-button>
          <a-button
            v-if="btn_auth.indexOf('4') != -1"
            style="margin-left: 10px"
            @click="shutdown"
          >强制结束</a-button>
          <a-button
            v-if="btn_auth.indexOf('5') != -1"
            style="margin-left: 10px"
            @click="toberead"
          >流程转阅</a-button>
          <a-button
            v-if="btn_auth.indexOf('6') != -1"
            style="margin-left: 10px"
            @click="printData"
          >打印</a-button>
        </span>
        <span v-else>
          <a-button type="primary" @click="resolveTask"> 完成 </a-button>
        </span>
      </div>
      <a-card

        style="width: 100%"
        :tab-list="cardList"
        :active-tab-key="activeKey"
        @tabChange="(key) => onTabChange(key, 'activeKey')"
      >
        <p v-show="activeKey === 'form'">
          <leaveInfo
            :business-key="record.businessKey"
            v-if="record.businessKey.indexOf('gencode:leave') != -1"
          />
          <chuchaiInfo
            :business-key="record.businessKey"
            v-if="record.businessKey.indexOf('gencode:chuchai') != -1"
          />
          <VDataCheck
            ref="checkRef"
            :record="record"
            @showloading="showloading"
            @finishResponse="finishResponse"
          />
        <!-- <k-form-build ref="kfb" :value="jsonData" v-if="record.businessKey.indexOf('customize') != -1" :dynamicData="dynamicData" /> -->
        </p>
        <p v-show="activeKey === 'flowchart'">
          <img :src="imageUrl" alt="流程图" class="image">
        </p>
        <p v-show="activeKey === 'processTrack'">
          <a-card class="card" title="当前节点信息" :bordered="false">
            <a-table
              :columns="actColumns"
              :data-source="actData"
              :pagination="false"
              bordered
            />
          </a-card>
          <a-card class="card" title="办理过程记录" :bordered="false">
            <a-table
              :columns="hisColumns"
              :data-source="hisData"
              :pagination="false"
              bordered
            />
          </a-card>
        </p>
      </a-card>
    </div>
  </div>
</template>
<script>
import {
  findActivityList,
  findActivityTaskList,
  completeCheck,
  rejectAnyNode,
  delegateTask,
  resolveTask,
  turnTask,
  shutdownTask,
  saveToberead,
} from '@/api/activiti/processTask'
import { findSettingInfo } from '@/api/activiti/nodesetting'
import axios from 'axios'
import VDataCheck from '@/views/customize/vdata/Check'
import leaveInfo from '@/views/gencode/leave/Info'
import chuchaiInfo from '@/views/gencode/chuchai/Info'
import Print from '@/views/activiti/processTask/Print'

import AssignmentForm from '@/views/activiti/processTask/Assignment'
import RejectNodeForm from '@/views/activiti/processTask/RejectNode'
import SelectOneUser from '@/views/system/User/SelectOneUser'
import SelectMoreUser from '@/views/system/User/SelectMoreUser'
import { formatDate } from '@/utils/date.js'
 import print from 'print-js'
const actColumns = [
  {
    title: '序号',
    dataIndex: '',
    customRender: function (t, r, index) {
      return parseInt(index) + 1
    },
  },
  {
    title: '环节名称',
    dataIndex: 'name',
    customRender: (text, row, index) => {
      if (text != null) {
        return text
      } else {
        return ''
      }
    },
  },
  {
    title: '当前办理人',
    dataIndex: 'assignee_name',
    customRender: (text, row, index) => {
      if (text != null) {
        return text
      } else {
        return ''
      }
    },
  },
  {
    title: '任务创建时间',
    dataIndex: 'createTime',
    customRender: (text, row, index) => {
      if (text != '' && text != null) {
        return formatDate(text)
      }
    },
  },
  {
    title: '办理状态',
    dataIndex: '',
    customRender: (text, row, index) => {
      if (row.assignee_name != null) {
        return '未完成'
      } else {
        if (row.claimTime == null) {
          return '未签收'
        } else {
          return '未完成（签收时间' + formatDate(row.claimTime);
          +'）'
        }
      }
    },
  },
  {
    title: '环节状态',
    dataIndex: 'suspensionState',
    ellipsis: true,
    customRender: (text, row, index) => {
      if (text == '1') {
        return '活跃状态'
      } else if (text == '2') {
        return '中断状态'
      }
    },
  },
  {
    title: '备注',
    dataIndex: 'owner_name',
    ellipsis: true,
    customRender: (text, row, index) => {
      if (text != '' && text != null) {
        return '所属人：' + text
      } else {
        return ''
      }
    },
  },
]

const hisColumns = [
  {
    title: '序号',
    dataIndex: '',
    customRender: function (t, r, index) {
      return parseInt(index) + 1
    },
  },
  {
    title: '环节类型',
    dataIndex: 'activityType',
    customRender: (text, row, index) => {
      if (text == 'startEvent') {
        return '开始节点'
      } else if (text == 'endEvent') {
        return '结束节点'
      } else if (text == 'userTask') {
        return '用户节点'
      } else {
        return '其他节点'
      }
    },
  },
  {
    title: '环节名称',
    dataIndex: 'activityName',
    customRender: (text, row, index) => {
      if (text != null) {
        return text
      } else {
        return ''
      }
    },
  },
  {
    title: '办理人',
    dataIndex: 'assignee_name',
    customRender: (text, row, index) => {
      if (text != null) {
        return text
      } else {
        return ''
      }
    },
  },
  {
    title: '办理意见',
    dataIndex: 'comment_msg',
    customRender: (text, row, index) => {
      if (text != null) {
        return text
      } else {
        return ''
      }
    },
  },
  {
    title: '办理开始时间',
    dataIndex: 'startTime',
    ellipsis: true,
    customRender: (text, row, index) => {
      if (text != '' && text != null) {
        return formatDate(text)
      }
    },
  },
  {
    title: '办理结束时间',
    dataIndex: 'endTime',
    ellipsis: true,
    customRender: (text, row, index) => {
      if (text != '' && text != null) {
        return formatDate(text)
      }
    },
  },
]

export default {
  // 声明当前子组件接收父组件传递的属性
  props: {
    record: {
      type: Object,
      default: null,
    },
  },
  data () {
    return {
      spinning: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      other: '',
      mybol: false,
      headers: {
        authorization: 'authorization-text',
      },
      uploading: false,
      form: {},
      cardList: [
        {
          key: 'form',
          tab: '表单',
        },
        {
          key: 'flowchart',
          tab: '流程图',
        },
        {
          key: 'processTrack',
          tab: '流程跟踪单',
        },
      ],
      activeKey: 'form',
      imageUrl: '',
      hisData: [],
      hisColumns,
      actData: [],
      actColumns,
      btn_auth: '',
      confirmLoadingV: false,
    }
  },
  components: {
    AssignmentForm,
    RejectNodeForm,
    VDataCheck,
    leaveInfo,
    chuchaiInfo,
    Print,
  },
  mounted () {
    if (this.record.id != undefined) {
      this.form = this.record
    }
    this.flowchart(this.record)
    this.activityList()
    this.nodeSetting(
      this.record.taskDefinitionKey,
      this.record.processInstanceId,
    )
  },
  methods: {
    nodeSetting (node_id, processInstanceId) {
      findSettingInfo({
        node_id: node_id,
        processInstanceId: processInstanceId,
      }).then((response) => {
        const data = response.data.data
        if (data != null) {
          this.btn_auth = data.btn_auth
        }
      })
    },
    onTabChange (key, activeKey) {
      this.activeKey = key
    },
    resetForm () {
      this.$refs.ruleForm.resetFields()
    },
    onOk () {
      return new Promise((resolve) => {
        resolve(true)
      })
    },
    onCancel () {
      return new Promise((resolve) => {
        resolve(true)
      })
    },
    activityList () {
      findActivityList({
        processInstanceId: this.record.processInstanceId,
      }).then((response) => {
        this.hisData = response.data.data.filter(
          (item) => item.endTime != null,
        )
      })

      findActivityTaskList({
        processInstanceId: this.record.processInstanceId,
      }).then((response) => {
        this.actData = response.data.data
      })
    },
    flowchart (record) {
      this.visible = true
      axios({
        method: 'GET',
        url:
          process.env.VUE_APP_API_BASE_URL +
          '/activiti/processTask/readResource?processInstanceId=' +
          record.processInstanceId,
        responseType: 'arraybuffer',
      })
        .then((res) => {
          return (
            'data:image/svg+xml;base64,' +
            btoa(
              new Uint8Array(res.data).reduce(
                (data, byte) => data + String.fromCharCode(byte),
                '',
              ),
            )
          )
        })
        .then((res) => {
          this.imageUrl = res
        })
        .catch((e) => {
          if (e.toString().indexOf('429') !== -1) {
            this.$notification.warning({
              message: '请求超时,请稍后重试',
              description: '',
            })
          } else {
            this.$notification.warning({
              message: '获取流程图失败',
              description: '',
            })
          }
        })
    },
    check () {
      const that = this
      const record = {
        processDefinitionKey: '',
        process_status: '1',
        taskId: this.record.id,
        processInstanceId: this.record.processInstanceId,
      }

      that.$refs.checkRef.getFormData().then((formatDate) => {
        console.log(5555)
        this.$dialog(
          AssignmentForm,
          {
            record: { ...record, ...formatDate },
            on: {
              complete (data, approve_opinion, skipNodes) {
                if (that.record.businessKey.indexOf('customize') != -1) {
                  that.$refs.checkRef.onOk({
                    ...that.record,
                    nodeData: data,
                    skipNodes: skipNodes,
                    approve_opinion: approve_opinion,
                  })
                } else {
                  completeCheck({
                    ...that.record,
                    nodeData: data,
                    skipNodes: skipNodes,
                    approve_opinion: approve_opinion,
                  }).then((response) => {
                    that.$emit('finishResponse', response)
                  })
                }
              },

            },

          },
          {
            title: '任务办理',
            width: 800,
            centered: true,
            maskClosable: false,
            okText: '确定',
            cancelText: '取消',
            mask: true,
            bodyStyle: {
              backgroundColor: '#f0f2f5',
              padding: '16px',
              border: '#FFFFFF 4px solid',
            },
          },
        )
      })
    },

    // 显示加载过渡
    showloading () {
      this.spinning = !this.spinning
    },
    finishResponse (response) {
      this.$emit('finishResponse', response)
    },
    backDown () {
      const record = {
        taskId: this.record.id,
      }
      const that = this
      this.$dialog(
        RejectNodeForm,
        {
          record,
          on: {
            complete (data,approve_opinion) {
              if (that.record.businessKey.indexOf('customize') != -1) {
                 
                that.$refs.checkRef.onRejectAnyNode({
                  ...that.record,
                  nodeData: data,
                  approve_opinion:approve_opinion,
                  flowElementId: data.activityId,
                })
              } else {
                 console.log('我执行驳回222')
                rejectAnyNode({

                  taskId: that.record.id,
                  flowElementId: data.activityId,
                }).then((response) => {
                  that.$emit('finishResponse', response)
                })
              }
            },
          },
        },
        {
          title: '流程驳回',
          width: 800,
          centered: true,
          maskClosable: false,
          okText: '确定',
          cancelText: '取消',
          bodyStyle: {
            backgroundColor: '#f0f2f5',
            padding: '16px',
            border: '#FFFFFF 4px solid',
          },
        },
      )
    },
    addSign () {
      const that = this
      const record = {
        user_id: '',
        user_name: '',
      }
      this.$dialog(
        SelectOneUser,
        {
          record,
          on: {
            ok () {},
            cancel () {},
            close () {},
            initValue (value, type) {
              if (that.record.businessKey.indexOf('customize') != -1) {
                that.$refs.checkRef.onDelegateTask({
                  taskId: that.record.id,
                  userId: value.split(':')[0],
                  userName: value.split(':')[1],
                })
              } else {
                delegateTask({
                  taskId: that.record.id,
                  userId: value.split(':')[0],
                  userName: value.split(':')[1],
                }).then((response) => {
                  that.$emit('finishResponse', response)
                })
              }
            },
          },
        },
        {
          title: '操作',
          width: 800,
          height: 500,
          centered: true,
          maskClosable: false,
          okText: '确认',
          cancelText: '取消',
        },
      )
    },
    resolveTask () {
      const that = this
      this.$confirm({
        title: '提示',
        content: '确定要完成任务吗？',
        onOk () {
          if (that.record.businessKey.indexOf('customize') != -1) {
            that.$refs.checkRef.onResolveTask({
              taskId: that.record.id,
            })
          } else {
            resolveTask({
              taskId: that.record.id,
            }).then((response) => {
              that.$emit('finishResponse', response)
            })
          }
        },
        onCancel () {},
      })
    },
    turnTask () {
      const that = this
      const record = {
        user_id: '',
        user_name: '',
      }
      this.$dialog(
        SelectOneUser,
        {
          record,
          on: {
            ok () {},
            cancel () {},
            close () {},
            initValue (value, type) {
              if (that.record.businessKey.indexOf('customize') != -1) {
                that.$refs.checkRef.onTurnTask({
                  taskId: that.record.id,
                  userId: value.split(':')[0],
                  userName: value.split(':')[1],
                })
              } else {
                turnTask({
                  taskId: that.record.id,
                  userId: value.split(':')[0],
                  userName: value.split(':')[1],
                }).then((response) => {
                  that.$emit('finishResponse', response)
                })
              }
            },
          },
        },
        {
          title: '操作',
          width: 800,
          height: 500,
          centered: true,
          maskClosable: false,
          okText: '确认',
          cancelText: '取消',
        },
      )
    },
    shutdown () {
      const that = this
      that.$confirm({
        title: '提示',
        content: (h) => <div style="color:red;">确定结束流程任务吗？</div>,
        okText: '确认',
        cancelText: '取消',
        onOk () {
          shutdownTask({ taskId: that.record.id }).then((response) => {
            if (response.data.success) {
              that.$success({
                title: '提示：',
                content: '流程任务结束成功',
                okText: '确认',
              })
              that.$emit('finishResponse', response)
            } else {
              this.$error({
                title: '提示：',
                content: response.data.msg,
                okText: '确认',
              })
            }
          })
        },
      })
    },
    // 流程转阅
    toberead () {
      const that = this
      const record = {
        user_ids: '',
        user_names: '',
      }
      this.$dialog(
        SelectMoreUser,
        {
          record,
          on: {
            ok () {},
            cancel () {},
            close () {},
            initValue (value, type) {
              saveToberead({
                title: that.record.start_user_name + '与' + formatDate(that.record.start_time) + '发起【' + that.record.procdef_name + '】的流程',
                taskId: that.record.id,
                userIds: value.split(':')[0],
                userNames: value.split(':')[1],
                businessKey: that.record.businessKey,
                node_id: that.record.taskDefinitionKey,
                node_name: that.record.name,
                processInstanceId: that.record.processInstanceId,
                process_name: that.record.procdef_name,
              }).then((response) => {
                 that.$success({
                    title: '提示：',
                    content: '流程转阅成功。',
                    okText: '确认',
                  })
                // that.$emit("finishResponse", response);
              })
            },
          },
        },
        {
          title: '操作',
          width: 800,
          height: 500,
          centered: true,
          maskClosable: false,
          okText: '确认',
          cancelText: '取消',
        },
      )
    },
    printData () {
      var record = {
        processInstanceId: this.record.processInstanceId,
        businessKey: this.record.businessKey,
      }
      this.$dialog(
        Print,
        // component props
        {
          record,
          on: {
            ok () {
              that.fetch({ pageSize: 10 })
              console.log('ok 回调')
            },
            cancel () {
              console.log('cancel 回调')
            },
            close () {
              console.log('modal close 回调')
            },
          },
        },
        // modal props
        {
          title: '详情',
          width: 1000,
          centered: true,
          maskClosable: false,
          footer: '',
        },
      )

      // const style = '@page {margin:0 10mm};'//打印时去掉眉页眉尾
      // //打印为什么要去掉眉页眉尾？因为眉页title时打印当前页面的title，相当于是获取html中title标签里面的内容，但是比如我打印的内容只是一个弹框里面的内容，是没有title的，这时候就会出现undefined，为了避免出现这种情况，就可以隐藏眉页眉尾
      // printJS({
      //   printable: this.$refs.printDiv,// 标签元素id
      //   type: 'html',
      //   header: '',
      //   targetStyles: ['*'],
      //   style
      // });
      // 各个配置项
      // printable:要打印的id。
      // type:可以是 html 、pdf、 json 等。
      // properties:是打印json时所需要的数据属性。
      // gridHeaderStyle和gridStyle都是打印json时可选的样式。
      // repeatTableHeader:在打印JSON数据时使用。设置为时false，数据表标题将仅在第一页显示。
      // scanStyles:设置为false时，库将不处理应用于正在打印的html的样式。使用css参数时很有用，此时自己设置的原来想要打印的样式就会失效，在打印预览时可以看到效果
      // targetStyles: [’*’],这样设置继承了页面要打印元素原有的css属性。
      // style:传入自定义样式的字符串，使用在要打印的html页面 也就是纸上的样子。
      // ignoreElements：传入要打印的div中的子元素id，使其不打印。非常好用
    },
  },
}
</script>
<style scoped>
.ant-modal-body {
  padding: 10px;
  font-size: 14px;
  line-height: 1.5;
  word-wrap: break-word;
}

.example {
  text-align: center;
  background: rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  margin-bottom: 20px;
  padding: 30px 50px;
  margin: 20px 0;
}
</style>
